var toPage;
laydate.render({
    elem: '#expire',
    type: 'datetime'
});
// 初始化用户列表
$(function () {
    userInfoValidation();
    getUserList();
    getRoleList();
    getOrgList();
});

$('#device_group_list').selectivity({
    items: [],
    multiple: true,
    placeholder: '选择数据范围'
});

$('#editInfoModal').on('hidden.bs.modal', function () {
    let form = $('#editInfoForm');
    form.data('bootstrapValidator').destroy();
    form.data('bootstrapValidator', null);
    userInfoValidation();
    form[0].reset();//清空表单
    resetForm(form);
    $('#device_group_list').selectivity({
        items: []
    });
    $('#device_group_list').selectivity('clear');
});

// 获取用户列表
function getUserList(_pageIndex) {
    showLoading(LOADING);
    let searchValue = $('#searchValue').val();
    let pageIndex = parseInt(_pageIndex ? _pageIndex : '1');
    toPage = pageIndex;
    getJson('/sys/user/list', {
            searchValue: searchValue,
            pageIndex: pageIndex,
            pageSize: 10
        }, 'GET', function (data) {
            if (data['code'] == 200) {
                let payload = data['payload'];
                setPage($('#page'), pageIndex, payload['pages'], payload['total'], function (num) {
                    getUserList(num);
                });
                let order = 1 + 10 * (pageIndex - 1);
                for (let item of payload['data']) {
                    item['order'] = order++;
                    if (!item['expire']) {
                        item['expire'] = '永久';
                    } else {
                        item['expire'] = getDate(item['expire']).datetime();
                    }
                }
                buildTable($('#userList'), title, label, data['payload']['data'], function (td, label, item) {
                    switch (label) {
                        case 'roleSet':
                            if (item[label].length > 0) {
                                $(td).text(item[label][0]['roleName']);
                            }
                            break;
                        case 'organization':
                            if (item[label]) {
                                $(td).text(item[label]['name']);
                            }
                            break;
                        case 'areaName':
                            let areaOrg = new Set();
                            let areaUser = new Set();
                            if (item['organization'] && item['organization']['area'].length > 0) {
                                areaOrg.add(item['organization']['area']);
                            } else {
                                areaOrg.add("");
                            }
                            if (item['area']) {
                                areaUser.add(item['area']);
                            }
                            let areaName = [];
                            if (item['areaSet']) {
                                for (let area of item['areaSet']) {
                                    areaName.push(area['name']);
                                }
                            }
                            let areaDiff = new Set([...areaOrg].filter(x => !areaUser.has(x)));
                            if (areaDiff.size == 0) {
                                $(td).text('全部');
                            } else {
                                $(td).text(areaName);
                            }
                            break;
                        case 'status':
                            $(td).empty();
                            let span = createElement('span', td);
                            if (item['status'] == 1) {
                                $(span).text('启用');
                                $(span).addClass('text-success');
                            } else {
                                $(span).text('禁用');
                                $(span).addClass('text-danger');
                            }
                            break;
                        case 'createTime':
                            $(td).empty();
                            $(td).text(getDate(item['createTime']).datetime());
                            break;
                        case 'desc':
                            $(td).empty();
                            $(td).text(item[label]);
                            break;
                        case 'opera':
                            if (sysUserOpera) {
                                let edit = createElement('a', td);
                                $(edit).addClass('font-p24');
                                let editIcon = createElement('i', edit);
                                $(editIcon).addClass('iconfont');
                                $(editIcon).addClass('icon-bianji-');
                                let del = createElement('a', td);
                                $(del).addClass('font-p24');
                                $(del).addClass('delete-option-btn');
                                $(del).addClass('ml-2');
                                let delIcon = createElement('i', del);
                                $(delIcon).addClass('iconfont');
                                $(delIcon).addClass('icon-shanchuicon');
                                if (item['readonly'] != 1) {
                                    $(edit).attr('href', '##');
                                    $(edit).click(function () {
                                        editUser(item['id']);
                                    });
                                    $(del).attr('href', '##');
                                    $(del).click(function () {
                                        delUser(item['id']);
                                    });
                                }
                            }
                            break;
                    }
                })
                hideLoading();
            } else {
                setPage($('#page'), pageIndex, 0, 0);
                myAlert('提示', data['message']);
                hideLoading();
            }
        }
    )
}

// 获取角色列表
function getRoleList() {
    getJson('/sys/role/getRoleList', {id: null}, 'GET', function (data) {
        buildSelect($('#role'), data['payload']['data'], 'roleName', 'id', '', function (option, item) {
            $(option).attr('type', item['type']);
            $(option).attr('expire', item['expire']);
        });
    })
}

$('#role').change(function () {
    let expire = $(this).find('option:selected').attr('expire');
    $('#expire').val(expire != 0 ? getDate(new Date(expire * 24 * 60 * 60 * 1000 + new Date().getTime()).getTime()).datetime() : '');
});

// 获取组织机构列表
function getOrgList() {
    getJson('/sys/org/list', {}, 'GET', function (data) {
        var resData = data.payload.data;
        resData.map(function (item, index) {
            item.text = item.name;
        });
        $('#company_list').selectivity({
            items: resData,
            placeholder: '选择组织'
        });
    });
}

$('#company_list').on('selectivity-selected', function (event) {
    setTimeout(() => {
        let val = event.id;
        $('#company_list_vld').val(val);
        $('#editInfoForm').data('bootstrapValidator').updateStatus('enterprise', 'NOT_VALIDATED', null).validateField('enterprise');//重置并触发字段的验证
        $('#areaDisplayName').val('');
        $('#editInfoForm').data('bootstrapValidator').updateStatus('areaDisplayName', 'NOT_VALIDATED', null).validateField('areaDisplayName');
        $('#area').val('');
        getGroupByArea([]);
        if (val) {
            getJson('/sys/org/getAreaById', {
                id: val
            }, 'GET', function (data) {
                buildAreaList($('#listGroup1'), data);
                data.map(function (item, index) {
                    item.text = item.name;
                });
            });
        } else {
            buildAreaList($('#listGroup1'));
        }
    }, 100);
});

/*添加用户*/
function addUser() {
    // 先清空
    resetForm($('#editInfoForm'));
    $('#company_list').selectivity('val', '');
    $('#editInfoModal').modal();
    $('#modal_title').text('添加用户');
    $('#username').attr('disabled', false);
    $('#listGroup1').empty();
}

/*修改用户信息*/
function editUser(id) {
    // 先清空
    resetForm($('#editInfoForm'));
    $('#company_list').selectivity('val', '');
    // 再填数据
    getJson('/sys/user/info', {id: id}, 'GET', function (data) {
        let user = data['payload']['data'];
        $('#id').val(user['id']);
        $('#username').val(user['username']);
        $('#displayName').val(user['displayName']);
        $('#status').val(user['status']);
        if (user['expire']) {
            $('#expire').val(getDate(user['expire']).datetime());
        }
        $('#desc').val(user['desc']);
        if (user.roleSet.length > 0) {
            $('#role').val(user.roleSet[0].id);
        }
        $('#company_list_vld').val(user.enterprise);
        $('#company_list').selectivity('val', user.enterprise);
        getJson('/sys/org/getAreaById', {//由组织id加载权限区域
            id: user.enterprise
        }, 'GET', function (data) {
            buildAreaList($('#listGroup1'), data, user.area);
            let ids = [];
            user.areaSet.map(function (item) {
                ids.push(item.id);
            });
            getGroupByArea(ids, user.deviceGroup);
        });
        let areaSet = [];
        if (user['areaSet']) {
            for (let item of user['areaSet']) {
                areaSet.push(item['name']);
            }
        }
        $('#areaDisplayName').val(areaSet.join(','));
        $('#editInfoForm').data('bootstrapValidator').updateStatus('areaDisplayName', 'NOT_VALIDATED', null).validateField('areaDisplayName');//重置并触发字段的验证
        $('#area').val(user['area']);
        $('#username').attr('disabled', true);
        $('#modal_title').text('修改用户信息');
        $('#editInfoModal').modal();
    });
}

/* 由权限区域加载数据范围-设备分组 */
function getGroupByArea(ids, selectedGroup) {
    if (ids && ids.length > 0) {
        getJson('/deviceGroup/getGroupByCompany', {//由所选权限区域加载数据范围列表
            ids: ids.join(',')
        }, 'GET', function (res) {
            let deviceGroup = [];
            res.payload.data.map(function (item) {
                deviceGroup.push({
                    id: item.id,
                    text: item.name
                });
            });
            $('#device_group_list').selectivity({
                items: deviceGroup
            });
            if (selectedGroup && selectedGroup.length > 0) {
                let selected = [];
                selectedGroup.map(function (item) {
                    selected.push(item.id);
                });
                $('#device_group_list').selectivity('value', selected);
                $('#device_group_list_vld').val(selected.join(','));
            } else {
                $('#device_group_list_vld').val('');
            }
        });
    } else {
        $('#device_group_list').selectivity({
            items: []
        });
        $('#device_group_list').selectivity('clear');
        $('#device_group_list_vld').val('');
    }
}

// 删除用户
function delUser(id) {
    myConfirm('提示', '是否删除用户', function (result) {
        if (result) {
            getJson('/sys/user/delete', {
                id: id
            }, 'GET', function (data) {
                getUserList(toPage);
                if (data['code'] == 200) {
                    myAlert('提示', '删除成功');
                } else {
                    myAlert('提示', data['message']);
                }
            })
        }
    })
}

//点击加载企业列表
$('#areaDisplayName').click(function () {
    $('#listGroup1').slideDown(0);
});

/*权限区域列表按钮操作*/
function confirmSelection() {//确认选择勾选企业
    $('#area').val('');
    $('#areaDisplayName').val('');
    var value = [];
    var name = [];
    $.each($('input:checkbox[name=companyList]:checked'), function () {
        value.push($(this).val());
        name.push($(this).attr('eName'))
    });
    $('#area').val(value.join(','));
    $('#areaDisplayName').val(name.join(','));
    getGroupByArea(value);
    $('#editInfoForm').data('bootstrapValidator').updateStatus('areaDisplayName', 'NOT_VALIDATED', null).validateField('areaDisplayName');//重置并触发字段的验证
    $('#listGroup1').slideUp(0);
}

function selectAll() {//全选
    $('input:checkbox[name=companyList]').prop("checked", true);
    confirmSelection();
}

function unselectAll() {//全不选
    $('input:checkbox[name=companyList]').prop("checked", false);
}

function cancelSelection() {//取消选择企业
    $('#listGroup1').slideUp(0);
}

function userInfoValidation() {
    $('#editInfoForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'fa fa-check',
            validating: 'fa fa-sync-alt'
        },
        fields: {
            displayName: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 16,
                    }
                }
            }, username: {
                validators: {
                    notEmpty: {},
                    regexp: {
                        regexp: /^([1]\d{10}|([\(（]?0[0-9]{2,3}[）\)]?[-]?)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?)$/,
                        message: '请输入正确的手机号'
                    }
                }
            }, role: {
                validators: {
                    callback: {
                        message: '必填项，不能为空',
                        callback: function (value, validator) {
                            if (!getSelectValue($('#role'))) {
                                return false;
                            } else {
                                return true;
                            }
                        }
                    }
                }
            }, enterprise: {
                validators: {
                    notEmpty: {}
                }
            }, areaDisplayName: {
                validators: {
                    notEmpty: {}
                }
            }
        }
    }).on('success.form.bv', function (e) {
        e.preventDefault();//阻止默认提交事件
        if (isNull($('#company_list_vld').val())) {
            myAlert("提示", "请选择归属组织");
            return;
        }
        showLoading("正在提交中");
        let formData = {
            id: $('#id').val(),
            username: $('#username').val(),
            displayName: $('#displayName').val(),
            role: getSelectValue($('#role')),
            expire: $('#expire').val(),
            enterprise: $('#company_list').selectivity('val'),
            area: $('#area').val(),
            group: $('#device_group_list').selectivity('val').join(','),
            status: $('#status').val(),
            desc: $('#desc').val()
        };
        getJson('/sys/user/save', formData, 'POST', function (data) {
            hideLoading();
            switch (data['code']) {
                case 200:
                    myAlert('提示', data['message'], function () {
                        $('#editInfoModal').modal('hide');
                        getUserList(toPage);
                    });
                    break;
                case 302:
                    myAlert('提示', data['message'], function () {
                        top.location.href = '../index.html';
                    });
                    break;
                default:
                    myAlert('提示', data['message']);
            }
        })
    }).on('error.form.bv', function (e) {//表单验证失败
        $('#editInfoForm [type="submit"]').removeAttr("disabled");
    });
}
